package com.neuedu.curd.controller;

import com.alibaba.fastjson.JSON;
import com.neuedu.curd.entity.User;
import com.neuedu.curd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目：springmvc-java4
 * 创建时间：  2022-03-24   16:48
 * 作者 :jshand
 * 描述 :
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/test")
    public String test(String str){
        System.out.println("UserController.test");
        System.out.println(str.length());
        return "/index.jsp";
    }


    /**
     *  http://127.0.0.1:8080/his/list
     * @param model
     * @return
     */
    @RequestMapping("list")
    public String  list(Model model){
        List<User> userList = userService.list();
        //把查询的结果放到request作用域
        model.addAttribute("userList",userList);

        return "/user/user_list";
    }

    /**
     * 跳转到添加
     * @return
     */
    @RequestMapping("toAdd")
    public String  toAdd(){
        return "/user/user_add";
    }

    @RequestMapping("toEdit")
    public String  toEdid(Integer id,Model model){

        User user = userService.queryById(id);
        model.addAttribute("user",user);

        return "/user/user_edit";
    }


    @RequestMapping("save")
    public String  save( User user){

        boolean success = userService.save(user);

        if(success){
            //重定向到查询请求
            return "redirect:/user/list";
        }else{
            //带着失败信息
            return "/user/user_add";
        }


    }

    @RequestMapping("update")
    public String  update( User user){

        boolean success = userService.update(user);

        if(success){
            //重定向到查询请求
            return "redirect:/user/list";
        }else{
            //带着失败信息
            return "/user/user_edit";
        }

    }


    /**
     * http://127.0.0.1:8080/his/user/deleteById?id=xx
     * @param id
     * @param response
     * @throws IOException
     */
    @RequestMapping("deleteById")
    public void  deleteById(Integer id, HttpServletResponse response) throws IOException {

        boolean success = userService.deleteById(id);

        Map map  = new HashMap();
        map.put("success",success);

        //响应json，为了给ajax
        String json = JSON.toJSONString(map);//{success:true/false}
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }









    
}
